package com.me.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.ActionMode;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.me.adapter.DBListAdapter;
import com.me.adapter.EventListAdapter;
import com.me.app.EventCreateActivity;
import com.me.app.R;

import android.view.Menu;

import com.me.data.DBItem;
import com.me.data.MeEvent;
import com.me.util.AppConstant;
import com.me.util.AppUtil;
import com.me.util.GenNotification;

import android.view.MenuItem;

public class DBPageFragment extends ListFragment {

	private int num;
	private ArrayList<DBItem> itemList;
	private DBListAdapter adapter;
	private HashMap<String, DBItem> seletedItems;

	public DBPageFragment(ArrayList<DBItem> itemList) {
		super();
		this.itemList = itemList;
		seletedItems = new HashMap<String, DBItem>();
	}

	public static DBPageFragment newInstance(ArrayList<DBItem> itemList,
			int num) {

		DBPageFragment fragment = new DBPageFragment(itemList);

		// Attach some data to it
		Bundle args = new Bundle();
		args.putInt(AppConstant.pagePosition, num);

		// Set the arguments on the fragment
		fragment.setArguments(args);
				
		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		num = getArguments() != null ? getArguments().getInt(
				AppConstant.pagePosition) : 0;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.event_list, container, false);
		v.setTag("#"+num);
		if (itemList.size() == 0)
			v.findViewById(R.id.event_list_empty).setVisibility(View.VISIBLE);
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		ListView listView = getListView();
		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
		listView.setMultiChoiceModeListener(new CustomMultiChoiceModeListener());
		
		adapter = new DBListAdapter(getActivity(), itemList);
		setListAdapter(adapter);
		
	}
	
	private void showConfirmDialog(String title, DialogInterface.OnClickListener positiveListener) {
	    TextView msg = new TextView(getActivity());
	    msg.setPadding(30,30,30,30);
	    msg.setGravity(Gravity.CENTER_VERTICAL);
	    msg.setTextSize(18);
		msg.setText(title);
		
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
		dialogBuilder.setView(msg);
		dialogBuilder.setPositiveButton("Yes", positiveListener);
		dialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int which) {
	        	dialog.cancel();
	        }
	    });
		dialogBuilder.show();
	}
	
	
	private class CustomMultiChoiceModeListener implements ListView.MultiChoiceModeListener {
	    @Override
	    public void onItemCheckedStateChanged(ActionMode mode, int position,long id, boolean checked) {
	    	
	    	ViewPagerFragment.getViewPager().setScrollable(false);
	    	DBItem dbItem = adapter.getItem(position);
			if (checked) {
				seletedItems.put(dbItem.getItemStringId(), dbItem);
			} else {
				seletedItems.remove(dbItem.getItemStringId());
			}
			mode.setTitle(String.valueOf(seletedItems.size()));
	    }

	    @Override
	    public boolean onActionItemClicked(final ActionMode mode, MenuItem item) {
	    	
			final int size = seletedItems.size();
			if (size == 0) 
				return false;
			
    		final String[] itemIDs = seletedItems.keySet().toArray(
    				new String[seletedItems.size()]);		
    		
    		final ArrayList<DBItem> dbItems = new ArrayList<DBItem>(seletedItems.values());

			switch (item.getItemId()) {
			case R.id.action_select_all:
				for (int i=0; i< adapter.getCount(); i++) {
					getListView().setItemChecked(i, true);
				}
				return true;

			case R.id.action_copy:
	    		
	    		StringBuffer infoBuffer = new StringBuffer();
				infoBuffer.append(dbItems.get(0).getName());
				for (int i = 1; i < size; i++){
					infoBuffer.append(", "+ dbItems.get(i).getName());
				}
				String formatedInfo = infoBuffer.toString();
					
				ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
				ClipData clip = ClipData.newPlainText("events", formatedInfo);
				clipboard.setPrimaryClip(clip);
				
				Toast.makeText(getActivity(), "Copy "+ size +" items", Toast.LENGTH_SHORT).show();			
				mode.finish(); 
				return true;
			case R.id.action_delete:
			    String deleteTitle = (size > 1)? "Do you want to delete " + size + " items?" 
			    		: AppConstant.DIALOG_TITLE_DELETE;
		
			    DialogInterface.OnClickListener deleteListener = new DialogInterface.OnClickListener() {
			        public void onClick(DialogInterface dialog,int which) {			            	 
			    		
						AppUtil.App.dataService.deleteItems(AppUtil.Event.eventType, itemIDs);
						
						for (int i=0; i< seletedItems.size(); i++)
							adapter.remove(dbItems.get(i));
												
						Toast.makeText(getActivity(), "Deleted" ,Toast.LENGTH_SHORT).show();
						notifyPendingChanged();
						mode.finish(); 
			        }
				};		
				showConfirmDialog(deleteTitle, deleteListener);
				return true;		
			default:
				return false;
			}
	    }

	    @Override
	    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
	        // Inflate the menu for the CAB
	        MenuInflater inflater = mode.getMenuInflater();
	        
	        inflater.inflate(R.menu.edit_db, menu);
	
	        return true;
	    }

	    @Override
	    public void onDestroyActionMode(ActionMode mode) {
	    	ViewPagerFragment.getViewPager().setScrollable(true);		// not allow page scrollable
	    	seletedItems.clear();
	    }

	    @Override
	    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
	        getListView().setOnItemClickListener(null);					//remove click listener
	        return false;
	    }
	}
	
	public void notifyPendingChanged() {
		GenNotification.show(getActivity().getPackageName(), getActivity());	
	}
}
